package com.zhang.zxx.boot.common.util;


import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * MyThreadFactory:自定义线程工厂
 * [这里使用了disruptor去处理IO密集型任务,主要是感受一下菱形操作,仅仅是测试感受一下,IO型任务处理还是多线程分批科学一些,所以这里只是用disruptor抛砖引玉]
 *
 * @author zhangxiaoxiang
 * @date 2021/04/16
 */
public class MyThreadFactory implements ThreadFactory {
    private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1);
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private String namePrefix = null;

    /**
     * 自定义的默认构造方法[简单套用ThreadPoolExecutor提供的默认工厂]
     */
    public MyThreadFactory() {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        namePrefix = "pool-" + POOL_NUMBER.getAndIncrement() + "-thread-";
    }

    /**
     * 线程重载构造方法
     *
     * @param prefix       模块[服务模块]
     * @param businessType 任务类别[具体业务]
     */
    public MyThreadFactory(String prefix, String businessType) {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        namePrefix = prefix + "-" + POOL_NUMBER.getAndIncrement() + "-" + businessType + "-";
    }

    /**
     * 线程重载构造方法
     * @param namePrefix 模块[服务模块]
     * @param taskType   任务类别[具体业务]
     */

    /**
     * 线程重载构造方法2
     *
     * @param prefix       模块[服务模块]
     * @param businessType 任务类别[具体业务]
     * @param threadType   IO/CPU 密集型
     */
    public MyThreadFactory(String prefix, String businessType, String threadType) {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        namePrefix = prefix + "-" + threadType + "-" + POOL_NUMBER.getAndIncrement() + "-" + businessType + "-";
    }

    /**
     * ThreadFactory 构造一个新的Thread 。 实现也可以初始化优先级，名称，守护程序状态， ThreadGroup等
     *
     * @param r Runnable
     * @return Thread
     */
    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
        if (t.isDaemon()) {
            t.setDaemon(false);
        }
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            t.setPriority(Thread.NORM_PRIORITY);
        }
        return t;
    }
}

